<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

     <el-row>
      <el-col :span="12">
        <el-form-item label="物资名称" prop="name">
        <el-input v-model="formData.name" :disabled="true" />  
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="物资编号" prop="assetCode"> 

          <el-input v-model="formData.assetCode" :disabled="true" />
        </el-form-item>
      </el-col>
     </el-row>
     
     <!--------------------------------------------------------以下是领用信息--------------------------------------------->
     <el-divider v-if="formData.oper == 'borrow'" content-position="left" class="blue-divider">领用信息</el-divider>
     <el-row v-if="formData.oper == 'borrow'">
      <el-col :span="12">
        <el-form-item label="领用人" prop="userIds" v-if="formData.oper == 'borrow'">
          <div class="flex flex-wrap gap-2">
            <div
              v-for="user in selectedUsers"
              :key="user.id"
              class="bg-gray-100 h-35px rounded-3xl flex items-center pr-8px dark:color-gray-600 position-relative"
            >
              <el-avatar class="!m-5px" :size="28" v-if="user.avatar" :src="user.avatar" />
              <el-avatar class="!m-5px" :size="28" v-else>
                {{ user.nickname.substring(0, 1) }}
              </el-avatar>
              {{ user.nickname }}
              <Icon
                icon="ep:close"
                class="ml-2 cursor-pointer hover:text-red-500"
                @click="handleRemoveUser(user)"
              />
            </div>
            <el-button type="primary" link @click="openUserSelect">
              <Icon icon="ep:plus" />选择人员
            </el-button>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="领用数量" prop="borrowedQuantity">
            <el-input-number v-model="formData.borrowedQuantity" :min="1" clearable controls-position="right" class="!w-1/1"/>
        </el-form-item>
      </el-col>
     </el-row>
     
      <el-form-item v-if="formData.oper == 'borrow'" label="备注" prop="inRemark" >
        <el-input v-model="formData.inRemark" type="textarea" placeholder="请输入备注" />
      </el-form-item>


      <!--------------------------------------------------------以下是补货信息--------------------------------------------->
      <el-divider v-if="formData.oper == 'restock'" content-position="left" class="blue-divider">补货信息</el-divider>
      <el-row v-if="formData.oper == 'restock'">
        <el-col :span="12">
          <el-form-item label="补货数量" prop="stockQuantity">
            <el-input-number v-model="formData.stockQuantity" :min="1" clearable controls-position="right" class="!w-1/1"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
         <el-form-item label="单价（元）" prop="price">
            <el-input-number v-model="formData.price" :min="0" clearable controls-position="right" class="!w-1/1"/>
          </el-form-item> 
        </el-col>
      </el-row>
      
      <el-form-item v-if="formData.oper == 'restock'" label="补货说明" prop="inRemark">
        <el-input v-model="formData.inRemark" type="textarea" placeholder="请输入说明" />
      </el-form-item>
   
      
    


    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

    <!-- 用户选择弹窗 -->
  <UserSelectForm
    ref="userSelectFormRef"
    isInitGet
    notSuccessMessage
    @confirm="handleUserSelectConfirm"
  />

</template>
<script setup lang="ts">
import { AssetsConsumableApi, AssetsConsumableVO } from '@/api/school/assets/consumable'
import { UserVO } from '@/api/system/user'
import { number } from 'vue-types'

/** 消耗型资产 表单 */
defineOptions({ name: 'AssetsFixedForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  assetCode: undefined,
  catetoryId: undefined,
  name: undefined,
  inRemark: undefined,
  userIds: undefined,
  price: undefined,  //单价
  oper: '',  //操作类型
  stockQuantity: 1, //库存数量
  borrowedQuantity: 0, //领用数量
})
const formRules = reactive({
  name: [{ required: true, message: '物资名称不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
  // inRemark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  stockQuantity: [{ required: true, message: '补货数量不能为空', trigger: 'blur' }],
  borrowedQuantity: [{ required: true, message: '领用数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const selectedUsers = ref<UserVO[]>([])
const userSelectFormRef = ref()

/** 处理用户选择确认 */
const handleUserSelectConfirm = (_, users: UserVO[]) => {
  selectedUsers.value = users || []
}

/** 打开人员选择 */
const openUserSelect = () => {
  userSelectFormRef.value.open(0, selectedUsers.value)
}

/** 移除人员 */
const handleRemoveUser = (user: UserVO) => {
  selectedUsers.value = selectedUsers.value.filter((userItem: any) => userItem.id !== user.id)
}


//窗口标题
const operMap = {
  borrow: '物资领用',
  restock: '补货',
}

/** 打开弹窗 */
const open = async (row:AssetsConsumableVO , oper: string) => {
  dialogVisible.value = true
  dialogTitle.value = operMap[oper] || '未知操作'
  resetForm()
  // 设置数据
  formLoading.value = true
  try {
    formData.value = await AssetsConsumableApi.getAssetsConsumable(row.id)
    formData.value.stockQuantity = null
    formData.value.borrowedQuantity = null
    formData.value.oper = oper
  } finally {
    formLoading.value = false
  }

}

watch(
  () => {
    return {
      formData: formData.value,
      userList: userSelectFormRef.value?.userList
    }
  },
  ({ formData, userList }: any) => {
    if (formData?.userIds?.length && userList?.length) {
      // 设置选中人员
      selectedUsers.value = userList.filter((userItem: any) =>
        formData.userIds.includes(userItem.id)
      )
    }
  },
  {
    deep: true
  }
)

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    //赋值领用人
    const userIds: any = selectedUsers.value?.map((user: any) => user.id)
    formData.value.userIds = userIds
    const data = formData.value as unknown as AssetsConsumableVO

    await AssetsConsumableApi.operAssetsConsumable(data)
    message.success(t('common.updateSuccess'))

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetCode: undefined,
    catetoryId: undefined,
    name: undefined,
    inRemark: undefined,
    userIds: undefined,
    price: undefined,  //维修费用
    oper: '',
    stockQuantity: 1, //库存数量
    borrowedQuantity: 0, //领用数量
  }
  formRef.value?.resetFields()
  //清空人员选择器
  selectedUsers.value = []
}


</script>

<style scoped>
:deep(.blue-divider .el-divider__text) {
  color: rgb(64, 158, 255);
}
</style>